package com.cskaoyan.utils;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.admin.Storage;
import com.cskaoyan.exception.wx_storage.FileIllegalArgumentException;
import lombok.SneakyThrows;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 类<code>Doc</code>用于：TODO 文件上传工具类
 *
 * @author Acher
 * @version 1.0
 * @date 2021-10-19
 */
public class FileUploadUtils {

    static String relativePath;

    /**
     * 方法<code>getStorageByFileUpload</code>作用为：上传文件并赋值StorageBean
     *
     * @author Acher
     * @param file
     * @throws
     * @return com.cskaoyan.bean.admin.Storage
     */
    @SneakyThrows
    public static Storage getStorageByFileUpload(MultipartFile file) {
        String filename = file.getOriginalFilename();
        // 生成随机文件名
        String uuid = UUID.randomUUID().toString();
        //文件后缀名
        String authName = uuid + filename;
        //  0x  4----1  ee1fffc------>
        //   770c4cce----->
        //   10000   100
        int hashCode = authName.hashCode();
        String hexString = Integer.toHexString(hashCode);
        char[] chars = hexString.toCharArray();
        relativePath = "";
        for (char aChar : chars) {
            relativePath = relativePath + "/" + aChar;
        }
        relativePath = relativePath + "/" + authName;
        String filePath = "D:/market/img/";// 如果没有d盘的可以根据自己情况创建路径
        File dest = new File(filePath + relativePath);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        file.transferTo(dest);
        String url = "http://192.168.7.18:8083/market/fetch/img" + relativePath;
        Storage storage = new Storage();
        storage.setKey(relativePath.substring(relativePath.lastIndexOf("/") + 1));
        storage.setName(filename);
        storage.setType(file.getContentType());
        storage.setSize(((int) dest.length()));
        storage.setUrl(url);
        ReflectionSetJavaBeanUtils.setJavaBean(storage);
        return storage;
    }
}
